package com.theorydance.esoperator.utils.impl;

import com.theorydance.esoperator.utils.SerializableCodec;

import java.io.*;

public class JdkSerializableCodec implements SerializableCodec {
    @Override
    public <T extends Serializable> byte[] serialize(T obj) {

        byte[] bytes = null;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)
        ) {
            objectOutputStream.writeObject(obj);
            bytes = byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    @Override
    public <T extends Serializable> T deserialize(byte[] bytes, Class<T> clazz) {
        T obj = null;
        try (
                ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))
        ) {
            obj = (T) in.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
